// subpackage_volleyball/knowledge_skills/knowledge_skills.ts

// 排球技能数据类型定义
interface VolleyballSkill {
  id: string;
  title: string;
  description: string;
  image: string;
  content: string;
  keyPoints: string[];
  tags?: string[];
  commonMistakes?: string[];
  practiceImage?: string;
  practiceSteps?: string[];
  progress?: number;
}

interface SkillCategory {
  categoryId: string;
  categoryName: string;
  skills: VolleyballSkill[];
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isDetailVisible: false,
    isQuickPracticeVisible: false,
    searchQuery: "",
    filteredCategories: [] as SkillCategory[],
    learningProgress: 35,
    latestSkillProgress: "已掌握扣球基础发力（60%）",
    selectedSkill: {
      id: "",
      title: "",
      description: "",
      image: "",
      content: "",
      keyPoints: [] as string[],
      tags: [] as string[],
      commonMistakes: [] as string[],
      practiceImage: "",
      practiceSteps: [] as string[],
      progress: 0,
    },
    // 用于存储展开的技能ID
    expandedSkills: [] as string[],
    quickPracticeSkill: {
      id: "",
      title: "",
      description: "",
      image: "",
      content: "",
      keyPoints: [] as string[],
      tags: [] as string[],
      commonMistakes: [] as string[],
      practiceImage: "",
      practiceSteps: [] as string[],
      progress: 0,
    },
    skillsCategories: [
      {
        categoryId: "basic_tech",
        categoryName: "基础技术体系",
        skills: [
          {
            id: "serve_receive",
            title: "一传技术",
            description: "排球一传的基础动作与实战技巧",
            image: "/static/images/knowledge_skill/pass_detail.jpg",
            content:
              "一传是排球比赛中最基础也最关键的技术环节，是组织进攻的第一步。良好的一传质量能够为二传创造更多战术选择空间，提高球队整体进攻效率。本课程将详细讲解一传的技术要点、移动方法和实战应对策略。",
            keyPoints: [
              "保持低重心的准备姿势",
              "准确判断来球的旋转和落点",
              "掌握多种移动步法快速到位",
              "根据二传位置调整传球方向和弧度",
            ],
            tags: ["基础", "一传"],
            commonMistakes: [
              "准备姿势过高，导致反应速度慢",
              "移动不及时，被迫在不利位置接球",
              "传球力量控制不当，难以组织有效进攻",
              "忽略来球旋转，导致判断失误",
            ],
            practiceImage:
              "/static/images/knowledge_skill/serve_receive_practice.gif",
            practiceSteps: [
              "准备姿势：双脚开立与肩同宽，膝盖微屈，重心降低",
              "判断与移动：观察发球方动作，快速移动到预判落点",
              "接球手型：双手重叠，手腕后仰，形成稳定的击球平面",
              "缓冲发力：根据来球力量调整缓冲力度，将球传向目标位置",
            ],
            progress: 65,
          },
          {
            id: "set_tech",
            title: "二传技术",
            description: "二传的手法控制与战术组织能力",
            image: "/static/images/knowledge_skill/pass_detail.jpg",
            content:
              '二传是球队进攻的核心组织者，被誉为"场上的教练"。优秀的二传手不仅需要精准的传球技术，更需要出色的战术意识和临场判断能力。本课程将深入讲解二传的基本手法、移动技巧和战术组织原则。',
            keyPoints: [
              "掌握多种传球手法（正传、背传、跳传等）",
              "提高视野范围，观察攻防两端情况",
              "根据攻手特点和比赛形势选择传球路线",
              "培养与攻手的默契配合",
            ],
            tags: ["核心", "组织"],
            commonMistakes: [
              "传球轨迹不稳定，影响攻手起跳时机",
              "观察不够全面，忽略场上变化",
              "战术选择单一，容易被对方针对性防守",
              "与攻手配合不够默契",
            ],
            practiceImage:
              "/static/images/knowledge_skill/set_tech_practice.gif",
            practiceSteps: [
              "手法练习：掌握各种传球手型和发力方法",
              "移动传球：结合不同方向的移动进行传球训练",
              "战术配合：与攻手进行各种战术组合的针对性练习",
              "实战模拟：在比赛环境中锻炼判断和决策能力",
            ],
            progress: 40,
          },
        ],
      },
      {
        categoryId: "offense_system",
        categoryName: "进攻战术体系",
        skills: [
          {
            id: "quick_attack_frame",
            title: "快攻战术框架",
            description: "排球快攻体系的构建与实施方法",
            image: "/static/images/knowledge_skill/attack_detail.jpg",
            content:
              "快攻战术是现代排球比赛中提高进攻节奏、打乱对方防守布局的重要手段。本课程将系统讲解快攻战术的基本框架、常用套路和训练方法，帮助球队建立高效的快攻体系。",
            keyPoints: [
              "快攻的基本站位与移动路线",
              "常用快攻战术（近体快、短平快、背快等）的技术要点",
              "二传与快攻手的默契配合训练",
              "快攻与后排进攻的结合运用",
            ],
            tags: ["快攻", "配合"],
            commonMistakes: [
              "二传传球时机和高度不合适",
              "攻手移动速度慢，与传球配合不协调",
              "快攻战术单一，缺乏变化",
              "忽略快攻后的跟进保护",
            ],
            practiceImage:
              "/static/images/knowledge_skill/quick_attack_frame_practice.gif",
            practiceSteps: [
              "基本配合：二传与攻手进行一对一的快攻配合练习",
              "多人间隔：增加参与人数，练习多人快攻体系",
              "战术变化：练习快攻的各种变化和掩护配合",
              "实战对抗：在比赛环境中应用和检验快攻战术",
            ],
            progress: 30,
          },
          {
            id: "pass_set_coordination",
            title: "传接协同",
            description: "一传与二传的衔接配合技巧",
            image: "/static/images/knowledge_skill/attack_detail.jpg",
            content:
              "传接协同是排球进攻体系的基础环节，直接影响到进攻的质量和效率。本课程将详细讲解一传与二传之间的沟通机制、移动配合和战术衔接技巧，帮助球队建立流畅的进攻组织流程。",
            keyPoints: [
              "一传与二传的沟通信号与默契培养",
              "根据一传质量灵活调整二传位置",
              "不同情况下的传接配合模式",
              "提高传接环节的稳定性和成功率",
            ],
            tags: ["配合", "衔接"],
            commonMistakes: [
              "一传到位率低，增加二传组织难度",
              "二传移动不及时，无法有效弥补一传不足",
              "双方沟通不畅，导致配合失误",
              "对特殊情况（如飘球、重发球）的应对能力不足",
            ],
            practiceImage:
              "/static/images/knowledge_skill/pass_set_coordination_practice.gif",
            practiceSteps: [
              "基础配合：固定位置的传接练习",
              "移动配合：模拟比赛中的各种移动传接场景",
              "特殊球处理：针对飘球、重发球等特殊情况的专项训练",
              "实战强化：在对抗训练中提高传接协同能力",
            ],
            progress: 45,
          },
        ],
      },
      {
        categoryId: "defense_counter",
        categoryName: "防守反击体系",
        skills: [
          {
            id: "blocking_system",
            title: "拦网技术",
            description: "现代排球拦网体系的构建与训练",
            image: "/static/images/knowledge_skill/block_detail.jpg",
            content:
              "拦网是防守的第一道防线，也是得分的重要手段。有效的拦网不仅可以直接得分，还能大幅减轻后排防守压力。本课程将系统讲解拦网的个人技术、集体配合和战术应用。",
            keyPoints: [
              "个人拦网的基本技术动作与发力方法",
              "拦网的预判与移动技巧",
              "集体拦网的协同配合",
              "针对不同进攻类型的拦网策略",
            ],
            tags: ["防守", "拦网"],
            commonMistakes: [
              "起跳时机不准确，被对方晃开",
              "拦网手型不正确，导致漏球",
              "集体拦网缺乏沟通，出现漏洞",
              "落地缓冲不足，容易造成运动损伤",
            ],
            practiceImage:
              "/static/images/knowledge_skill/blocking_system_practice.gif",
            practiceSteps: [
              "个人技术：练习拦网的基本动作和手型",
              "移动拦网：结合不同方向的移动进行拦网训练",
              "集体配合：2-3人间的拦网协同练习",
              "实战应用：在比赛环境中提高拦网判断和配合能力",
            ],
            progress: 50,
          },
          {
            id: "backcourt_defense",
            title: "后排防守",
            description: "排球后排防守的体系构建与训练",
            image: "/static/images/knowledge_skill/defense_detail.jpg",
            content:
              "后排防守是排球比赛中不可或缺的环节，良好的后排防守能够有效遏制对方进攻并为反攻创造机会。本课程将详细讲解后排防守的站位、移动、判断和接球技术。",
            keyPoints: [
              "后排防守的基本站位与区域划分",
              "快速移动和取位技巧",
              "不同类型来球的防守方法",
              "防守与反攻的衔接转换",
            ],
            tags: ["防守", "后排"],
            commonMistakes: [
              "站位不合理，出现防守漏洞",
              "移动不及时，导致防守位置不当",
              "重心过高，反应速度慢",
              "防守后的衔接意识不足",
            ],
            practiceImage:
              "/static/images/knowledge_skill/backcourt_defense_practice.gif",
            practiceSteps: [
              "基本站位：学习后排防守的标准阵型和位置",
              "移动训练：练习各种方向的快速移动和取位",
              "接球技术：掌握垫球、传球等防守接球技巧",
              "防反衔接：练习防守后的快速反击组织",
            ],
            progress: 55,
          },
        ],
      },
      {
        categoryId: "scenario_tactics",
        categoryName: "场景化战术应用",
        skills: [
          {
            id: "school_match_tactics",
            title: "校园比赛战术",
            description: "适合校园排球比赛的实用战术体系",
            image: "/static/images/knowledge_skill/quick_attack_detail.jpg",
            content:
              "校园排球比赛具有独特的特点，如队员水平参差不齐、配合时间有限等。本课程将针对校园比赛的实际情况，介绍简单实用、易于掌握的战术体系，帮助校园球队在比赛中取得更好的成绩。",
            keyPoints: [
              "校园比赛的特点与战术设计原则",
              "简单高效的进攻战术组合",
              "实用的防守体系构建",
              "根据队员特点进行战术调整",
            ],
            tags: ["校园", "实用"],
            commonMistakes: [
              "战术过于复杂，队员难以掌握",
              "忽略基本技术的重要性",
              "缺乏灵活调整能力，过于死板",
              "团队配合不够默契",
            ],
            practiceImage:
              "/static/images/knowledge_skill/school_match_tactics_practice.gif",
            practiceSteps: [
              "基础阵型：学习校园比赛的基本站位和阵型",
              "简单配合：练习2-3种核心战术配合",
              "针对性训练：根据队员特点进行个性化训练",
              "模拟比赛：在实战环境中应用和检验战术",
            ],
            progress: 35,
          },
          {
            id: "recreational_court_tactics",
            title: "野球场战术",
            description: "非正式比赛环境下的灵活战术应用",
            image: "/static/images/knowledge_skill/quick_attack_detail.jpg",
            content:
              "野球场排球是大众参与排球运动的主要形式，具有规则灵活、人员不固定等特点。本课程将介绍适合野球场环境的灵活战术和应对策略，帮助你在各种非正式比赛中发挥更好的水平。",
            keyPoints: [
              "野球场比赛的特点与规则灵活应用",
              "快速适应不同队友的特点和水平",
              "简单有效的临时配合方式",
              "根据场地和人员情况调整战术",
            ],
            tags: ["野球场", "灵活"],
            commonMistakes: [
              "对队友期望过高，导致配合失误",
              "战术选择不切实际，难以执行",
              "缺乏沟通，场上混乱",
              "不适应对手的非常规打法",
            ],
            practiceImage:
              "/static/images/knowledge_skill/recreational_court_tactics_practice.gif",
            practiceSteps: [
              "快速了解：比赛前快速了解队友特点和水平",
              "简单沟通：建立基本的场上沟通方式",
              "基础配合：练习1-2种简单有效的配合模式",
              "灵活调整：根据比赛进程及时调整战术",
            ],
            progress: 25,
          },
        ],
      },
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    console.log("排球知识技能页面加载完成");
    // 初始化数据确保页面显示
    this.setData({
      filteredCategories: this.data.skillsCategories,
    });

    // 计算整体学习进度
    this.calculateLearningProgress();
  },

  /**
   * 页面滚动时的处理函数
   */
  onPageScroll() {
    try {
      // 简化的滚动动画实现
      const query = wx.createSelectorQuery();
      query
        .selectAll(".skill-item")
        .fields({ node: true, rect: true })
        .exec((res) => {
          if (res && res[0] && res[0].length) {
            const windowHeight = wx.getSystemInfoSync().windowHeight;
            res[0].forEach((item: any) => {
              // 确保元素和样式对象存在
              if (item.node && item.node.style && item.rect && item.rect.top < windowHeight - 100) {
                try {
                  item.node.style.opacity = "1";
                  item.node.style.transform = "translateY(0)";
                  item.node.style.transition = "opacity 0.5s ease, transform 0.5s ease";
                } catch (error) {
                  console.error("应用动画样式失败:", error);
                }
              }
            });
          }
        });
    } catch (error) {
      console.error("页面滚动动画处理错误:", error);
    }
  },

  /**
   * 进入页面时的动画效果
   */
  onShow() {
    console.log("排球知识技能页面显示");
    try {
      // 为每个技能项添加初始动画样式
      const query = wx.createSelectorQuery();
      query
        .selectAll(".skill-item")
        .fields({ node: true })
        .exec((res) => {
          if (res && res[0]) {
            res[0].forEach((element: any, _index: number) => {
              // 确保元素和样式对象存在
              if (element && element.style) {
                try {
                  element.style.opacity = "0";
                  element.style.transform = "translateY(20px)";
                } catch (error) {
                  console.error("设置初始动画样式失败:", error);
                }
              }
            });

            // 延迟执行动画，确保样式已应用
            setTimeout(() => {
              this.onPageScroll({ scrollTop: 0 });
            }, 100);
          }
        });
    } catch (error) {
      console.error("初始化页面动画错误:", error);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log("排球知识技能页面渲染完成");
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log("排球知识技能页面隐藏");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log("排球知识技能页面卸载");
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    console.log("下拉刷新");
    // 模拟数据刷新
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log("上拉触底");
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: "排球知识技能",
      path: "/subpackage_volleyball/knowledge_skills/knowledge_skills",
    };
  },

  /**
   * 导航到首页
   */
  navigateToHome() {
    wx.redirectTo({
      url: "/pages/index/index",
    });
  },

  /**
   * 返回上一页
   */
  navigateBack() {
    wx.navigateBack({
      delta: 1,
    });
  },

  /**
   * 搜索输入处理
   */
  onSearchInput(e: any) {
    const query = e.detail.value;
    this.setData({
      searchQuery: query,
    });

    // 实时搜索
    this.filterSkills(query);
  },

  /**
   * 搜索确认处理
   */
  onSearchConfirm() {
    this.filterSkills(this.data.searchQuery);
  },

  /**
   * 清除搜索
   */
  clearSearch() {
    this.setData({
      searchQuery: "",
      filteredCategories: this.data.skillsCategories,
    });
  },

  /**
   * 筛选技能
   */
  filterSkills(query: string) {
    if (!query.trim()) {
      this.setData({
        filteredCategories: this.data.skillsCategories,
      });
      return;
    }

    const lowerQuery = query.toLowerCase();
    const filtered = this.data.skillsCategories
      .map((category) => {
        const filteredSkills = category.skills.filter(
          (skill) =>
            skill.title.toLowerCase().includes(lowerQuery) ||
            skill.description.toLowerCase().includes(lowerQuery) ||
            (skill.tags &&
              skill.tags.some((tag) => tag.toLowerCase().includes(lowerQuery)))
        );

        return {
          ...category,
          skills: filteredSkills,
        };
      })
      .filter((category) => category.skills.length > 0);

    this.setData({
      filteredCategories: filtered,
    });
  },

  /**
   * 显示技能详情（修改为直接显示模态框）
   */
  showSkillDetail(e: any) {
    try {
      // 阻止事件冒泡
      if (e && typeof e.stopPropagation === 'function') {
        e.stopPropagation();
      }
    } catch (error) {
      console.log('阻止冒泡失败:', error);
    }
    
    // 获取技能ID
    const { id } = e.currentTarget.dataset;
    
    // 查找对应的技能信息以获取分类ID
    let categoryId = '';
    for (const category of this.data.skillsCategories) {
      const skill = category.skills.find(s => s.id === id);
      if (skill) {
        categoryId = category.categoryId;
        break;
      }
    }
    
    // 跳转到技能详情页面
    wx.navigateTo({
      url: `/subpackage_volleyball/knowledge_skills/skill_detail?id=${id}&categoryId=${categoryId}`
    });
  },

  /**
   * 显示快速试练
   */
  showQuickPractice(e: any) {
    const { id } = e.currentTarget.dataset;
    let skill = null;

    // 阻止事件冒泡，避免同时触发showSkillDetail
    e.stopPropagation();

    // 从分类中查找技能
    for (const category of this.data.skillsCategories) {
      const foundSkill = category.skills.find((item) => item.id === id);
      if (foundSkill) {
        skill = foundSkill;
        break;
      }
    }

    if (skill) {
      this.setData({
        quickPracticeSkill: skill,
        isQuickPracticeVisible: true,
      });
    }
  },

  /**
   * 标记为已练习
   */
  markAsCompleted(e: WechatMiniprogram.TouchEvent) {
    const { id } = e.currentTarget.dataset;

    // 更新技能进度
    const updatedCategories = this.data.skillsCategories.map((category) => {
      return {
        ...category,
        skills: category.skills.map((skill) => {
          if (skill.id === id) {
            // 模拟进度更新，实际应用中可以根据练习情况调整
            const newProgress = Math.min(100, (skill.progress || 0) + 10);
            return {
              ...skill,
              progress: newProgress,
            };
          }
          return skill;
        }),
      };
    });

    this.setData({
      skillsCategories: updatedCategories,
      filteredCategories: updatedCategories,
      isQuickPracticeVisible: false,
    });

    // 重新计算整体学习进度
    this.calculateLearningProgress();

    // 显示成功提示
    wx.showToast({
      title: "练习完成，进度已更新",
      icon: "success",
      duration: 2000,
    });
  },

  /**
   * 计算学习进度
   */
  calculateLearningProgress() {
    let totalSkills = 0;
    let completedSkills = 0;
    let latestProgress = "";

    // 计算总进度
    this.data.skillsCategories.forEach((category) => {
      category.skills.forEach((skill) => {
        totalSkills++;
        const progress = skill.progress || 0;
        completedSkills += progress;

        // 记录最近的进度信息
        if (progress > 0 && progress < 100) {
          latestProgress = `已掌握${skill.title}（${progress}%）`;
        }
      });
    });

    const overallProgress =
      totalSkills > 0 ? Math.round(completedSkills / totalSkills) : 0;

    this.setData({
      learningProgress: overallProgress,
      latestSkillProgress: latestProgress || "开始你的排球技能学习之旅吧！",
    });
  },

  /**
   * 前往详细练习
   */
  goToPractice(_e: WechatMiniprogram.TouchEvent) {
    // 获取练习ID
    // 目前仅显示提示，未来可根据ID实现页面跳转
    // 在实际应用中，这里可以跳转到详细的练习页面
    // 目前仅显示提示
    wx.showToast({
      title: "跳转到详细练习页面",
      icon: "none",
      duration: 2000,
    });

    // 关闭详情弹窗
    this.closeDetailModal();
  },

  /**
   * 关闭详情弹窗
   */
  closeDetailModal() {
    this.setData({
      isDetailVisible: false,
    });
  },

  /**
   * 关闭快速试练弹窗
   */
  closeQuickPractice() {
    this.setData({
      isQuickPracticeVisible: false,
    });
  },
});
